package com.justech.mes.utils.plugins.transfer;

import com.justech.mes.utils.plugins.transfer.annotation.Format;
import com.justech.mes.utils.plugins.transfer.annotation.Import;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author feifei.li
 */
public abstract class AbstractProcesser implements Processer {

    @Override
    public <T> T process(T source) {
        Class<?> oClass = source.getClass();
        Field[] declaredFields = oClass.getDeclaredFields();
        for (Field f : declaredFields) {
            f.setAccessible(true);
            Object o = ReflexUtilSandBox.getValue(f, source);
            Annotation[] annotations = f.getAnnotations();
            for (Annotation annotation : annotations) {
                o = processSingleType(o, annotation);
            }
            ReflexUtilSandBox.setValue(f, source, o);
        }
        return source;
    }

    @Override
    public Object processSingleType(Object singleType, Annotation annotation) {
        return DispatchConverter.entry(new Annotation[]{annotation}, singleType);
    }

    protected boolean isMarked(Annotation[] annotations) {
        for (Annotation annotation : annotations) {
            if (annotation instanceof Format
                    || annotation instanceof Import) {
                return true;
            }
            if (annotation.annotationType().getAnnotation(Import.class) != null) {
                return true;
            }
        }
        return false;
    }
}
